from flask import g
from playhouse.shortcuts import model_to_dict

from apps.models.public import EnumData
from apps.models.user import UserRole, Permission
from apps.utils.views import get_page


def get_enum_list():
    data = {'items': []}
    conditions = [EnumData.is_del == False]
    if getattr(g, 'search_type', None):
        conditions.append(EnumData.type == g.search_type)
    query = EnumData.select().where(*conditions)
    if g.page:
        data['page'] = get_page(query)
        query = query.paginate(g.page, g.per_page)
    for enum in query:
        data['items'].append(enum.get_standard_obj())
    return data


def get_all_permission(parent_id=None):
    permissions = Permission.select().where(Permission.is_del == False,
                                            Permission.enable == True,
                                            Permission.parent_id == parent_id,
                                            Permission.visible == True)
    result = []
    for permission in permissions:
        if permission.code != 'system:*:*':
            menu = {'label': permission.name, 'value': permission.id}
            children = get_all_permission(permission.id)
            if children:
                menu['child'] = children
            result.append(menu)
    return result
